<template>
  <button class="btn-ghost"
    ref="msgCode"
    :class="classType"
    :disabled="classType === 'disabled'"
    @click.prevent="onGetCode">
    获取验证码
  </button>
</template>

<script>
// 定时器执行间隔时间
const TIMER_INTERVAL = 60

export default {
  props: {
    type: { // default, main
      type: String,
      default: 'main'
    },
    clickable: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    clickable() {
      if (!this.clickable) {
        this.classType = 'main'
        this.$refs.msgCode.innerHTML = '获取验证码'
        this.msgCodeTime = TIMER_INTERVAL
        window.clearInterval(this.intervalObj)
      }
    }
  },
  data() {
    return {
      msgCodeTime: TIMER_INTERVAL,
      intervalObj: '',
      classType: (this.type || !clickable)
    }
  },
  methods: {
    onGetCode() {
      // 设置点击了
      this.$emit('on-click')

      // 如果外面传入的状态是不可点击，则不能点击
      if (!this.clickable) {
        return
      }

      const oTarget = this.$refs.msgCode

      if (this.msgCodeTime === 0) {
        this.classType = 'main'
        oTarget.innerHTML = '获取验证码'
        this.msgCodeTime = TIMER_INTERVAL
      } else {
        this.classType = 'disabled'
        oTarget.innerHTML = `重新发送${this.msgCodeTime}s`

        // 设置定时器
        this.setTimer(oTarget)
      }
    },

    /**
     * 设置定时器
     */
    setTimer(oTarget) {
      // 如果定时器不存在，则初始化一个定时器
      if (!this.intervalObj) {
        // 采用定时器
        this.intervalObj = setInterval(() => {
          // 如果倒计时没结束，则继续倒计时
          if (this.msgCodeTime > 0) {
            this.msgCodeTime--
            this.classType = 'disabled'
            oTarget.innerHTML = `重新发送${this.msgCodeTime}s`
            return
          }

          // 将可点击状态设置为可点击
          this.classType = 'main'

          // 将提示字设置为获取
          oTarget.innerHTML = '获取验证码'

          // 重新设置时间
          this.msgCodeTime = TIMER_INTERVAL

          // 如果倒计时完毕，则清除定时器
          window.clearInterval(this.intervalObj)
          this.intervalObj = ''
        }, 1000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-ghost.disabled {
  height: 46px;
}
</style>